
#include <stdlib.h>
#include <video.h>
#include <inout.h>

int video_mem = 0xb8000;
short cursor = 0;
char color = 0x01;    /* Blue on text. */

/*
 * Colors are:
 * Val     Color
 * --------------
 * 0x00    black
 * 0x01    blue
 * 0x02    green
 * 0x03    cyan
 * 0x04    red
 * 0x05    magenta
 * 0x06    brown
 * 0x07    gray
 * 0x08    dark grey
 * 0x09    bright blue
 * 0x0a    bright green
 * 0x0b    bright cyan
 * 0x0c    pink
 * 0x0d    bright magenta
 * 0x0e    yellow
 * 0x0f    white
 */


void k_printc(char c){

  unsigned char *draw_loc = (unsigned char *) video_mem;
  draw_loc += (cursor * 2);
  *draw_loc = c;
  *(draw_loc + 1) = color;
  cursor++;

  /* Now move the real cursor to the location the next char will be */
  /* outputted.                                                     */
  __move_cursor();

}

void k_cprintc(char c, char col){

  unsigned char *draw_loc = (unsigned char *) video_mem;
  draw_loc += (cursor * 2);
  *draw_loc = c;
  *(draw_loc + 1) = col;
  cursor++;

  /* Now move the real cursor to the location the next char will be */
  /* outputted.                                                     */
  __move_cursor();

}

void k_printl(){

  int d_curs = cursor % 80;       // d_curs is remainder of (cursor / 80), ie
                                  // how far into the current line cursor is.
  d_curs = 80 - d_curs;           // Find out how far til the end of the line.
  cursor += d_curs;

  __move_cursor();

}

void k_print(char *str){
  
  int len = strlen(str);
  int i = 0;
  for ( ; i < len; i++){
    if (str[i] == '\n') k_printl();
    else {
      k_printc(str[i]);
    }
  }
  
}

void k_cprint(char col, char *str){

  int len = strlen(str);
  int i = 0;
  for ( ; i < len; i++){
    if (str[i] == '\n') k_printl();
    else {
      k_cprintc(str[i], col);
    }
  }

}

void k_clear_scr(){

  unsigned char *vidmem = (unsigned char *) video_mem;
  int i;
  for ( i = 0; i < 2000; i++){
    *vidmem++ = 0;
    *vidmem++ = color;
  }

  cursor = 0;
  __move_cursor();

}

char k_set_color(char new_col){

  char b_col = color;  // Return this.
  color = new_col;
  return b_col;

}

void __move_cursor(){

  /* First find the H/L order bytes of the cursor location. */
  short real_cursor = cursor;
  unsigned char *bytes = (unsigned char *) &real_cursor;
  /*__mov_cursor(bytes[1], bytes[0]);*/
  __out_c(0x3d4, 14);
  __out_c(0x3d5, bytes[1]);
  __out_c(0x3d4, 15);
  __out_c(0x3d5, bytes[0]);

}
